<template>
	<view>

		<view class="img">
			<image class="banner" src="/static/banner/1.jpeg" mode="top"></image>
		</view>

		<view>音频时长:{{s}}秒</view>
		<view>已播放:{{current}}秒</view>
		<progress :percent="per" show-info />
		<button @click="play">
			播放
		</button>
		<button @click="pause">
			暂停
		</button>
		<button @click="stop">
			停止
		</button>

	</view>
</template>

<script>
	import {
		ref,
		toRefs,
		reactive
	} from 'vue';
	export default {
		setup() {

			const state = reactive({
				s: 0,
				current: 0,
				per: 0,
				step: 0 //步长
			})

			const innerAudioContext = uni.createInnerAudioContext();
			// innerAudioContext.autoplay = true;
			innerAudioContext.src =
				'https://bjetxgzv.cdn.bspapp.com/VKCEYUGU-hello-uniapp/2cc220e0-c27a-11ea-9dfb-6da8e309e0d8.mp3';
			innerAudioContext.onPlay(() => {
				console.log('开始播放');
			});
			innerAudioContext.onError((res) => {
				console.log(res.errMsg);
				console.log(res.errCode);
			});
			innerAudioContext.onPause(() => {
				console.log("已暂停")
			});
			innerAudioContext.onStop(() => {
				console.log("已停止")
				state.per = 0;
			})
			innerAudioContext.onCanplay(() => {
				state.s = innerAudioContext.duration;
				state.step = 100 / state.s;
			})
			innerAudioContext.onTimeUpdate(() => {
				state.current = innerAudioContext.currentTime;
				state.per = (state.current * state.step).toFixed(2);
			})

			innerAudioContext.onEnded(() => {
				state.per = 100;
			})

			//播放
			const play = () => {
				innerAudioContext.play();
			}

			//暂停
			const pause = () => {
				innerAudioContext.pause();
			}

			//停止
			const stop = () => {
				innerAudioContext.stop();
			}

			return {
				play,
				pause,
				stop,
				...toRefs(state)
			}

		}
	}
</script>

<style scoped>
	.img {
		width: 300rpx;
		height: 300rpx;
		border: 1rpx solid red;
	}

	.banner {
		width: 100%;
		height: 100%;
	}
</style>
